package net.kesumu.yushabu;

import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Locale;

import net.kesumu.general.android.EasyStorage.EasyStorage;
import net.kesumu.general.android.view.BackgroundUtil;
import net.kesumu.general.android.view.CustomStatusBar;
import net.kesumu.yushabu.utils.JSONUtil;
import net.kesumu.yushabu.utils.WsConfig;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.codebutler.android_websockets.WebSocketClient;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.message.PushAgent;

public class MyInfoActivity extends Activity {
    
    private EasyStorage mEasyStorage;

    ImageView mPhotoView;
    TextView mNameView;
    TextView mIdView;
    TextView mSignatureView;
    TextView mGenderView;
    TextView mAreaView;

    String mMyPhotoPath;
    String mMyName;
    String mMyId;
    String mMySignature;
    String mMyGender;
    String mMyArea;
    String mYuYuChatId;
    
    //Upload photo
    ProgressDialog prgDialog;
    String encodedString;
    RequestParams params = new RequestParams();
    String imgPath, fileName;
    Bitmap bitmap;
    private static int RESULT_LOAD_IMG = 1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        getActionBar().setCustomView(R.layout.actionbar);
        ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.title_activity_my_info));
        //Custom the status bar
        CustomStatusBar customStatusBar = new CustomStatusBar(this);
        customStatusBar.setStatusBarColor(findViewById(R.id.statusBarBackground), getResources().getColor(R.color.main));


        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mMyPhotoPath = mEasyStorage.getString("mMyPhotoPath");
        mMyName = mEasyStorage.getString("mMyName");
        mMyId = mEasyStorage.getString("mMyId");
        mMySignature = mEasyStorage.getString("mMySignature");
        mMyGender = mEasyStorage.getString("mMyGender");
        mMyArea = mEasyStorage.getString("mMyArea");
        mYuYuChatId = mEasyStorage.getString("mYuYuChatId");
        
//        showToast("[1]"+mMyPhotoPath);
        
        
        prgDialog = new ProgressDialog(this);
        // Set Cancelable as False
        prgDialog.setCancelable(false);
//        startUpClient();
        
        PushAgent.getInstance(this).onAppStart();
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        mPhotoView = (ImageView) findViewById(R.id.image_photo_mine);
        mNameView = (TextView) findViewById(R.id.text_name_mine);
        mIdView = (TextView) findViewById(R.id.text_id_mine);
        mSignatureView = (TextView) findViewById(R.id.text_signature_mine);
        mGenderView = (TextView) findViewById(R.id.text_gender_mine);
        mAreaView = (TextView) findViewById(R.id.text_area_mine);

        if(mMyPhotoPath != null && !mMyPhotoPath.equalsIgnoreCase("")) {
            String mMyPhotoName = mMyPhotoPath.substring(0, mMyPhotoPath.indexOf("."));
            String mMyPhotoExtention = mMyPhotoPath.substring(mMyPhotoPath.indexOf(".")+1);
            Bitmap photo_mine = mEasyStorage.getImageBitmap(mMyPhotoName, mMyPhotoExtention);
            mPhotoView.setImageBitmap(photo_mine);
        }
        
        Bitmap photo_mine = ((BitmapDrawable)(mPhotoView.getDrawable())).getBitmap();
        View background_photo_mine = findViewById(R.id.background_photo_mine);
        background_photo_mine.setBackgroundColor(BackgroundUtil.getAverageColor(photo_mine));
        
        if(mMySignature != null) {
            findViewById(R.id.waiting).setVisibility(View.GONE);
        }
    }
    
    @Override
    protected void onResume() {
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mMyPhotoPath = mEasyStorage.getString("mMyPhotoPath");
        
        mMyName = mEasyStorage.getString("mMyName");
        mYuYuChatId = mEasyStorage.getString("mYuYuChatId");
        mMySignature = mEasyStorage.getString("mMySignature");
        mMyGender = mEasyStorage.getString("mMyGender");
        mMyArea = mEasyStorage.getString("mMyArea");
        
        
        mNameView.setText(mMyName);
        mIdView.setText(mYuYuChatId);
        mSignatureView.setText(mMySignature);
        mGenderView.setText(mMyGender);
        mAreaView.setText(mMyArea);
        super.onResume();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my_info, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_modifyPhoto) {
            uploadImage(findViewById(R.id.btn_upload));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my_info,
                    container, false);
            return rootView;
        }
    }
    
    
    
    
    public void editPhoto(View clickedView) {
        
    }
    
    public void editName(View clickedView) {
        Intent editInfoActivity = new Intent(MyInfoActivity.this, EditInfoActivity.class);
        editInfoActivity.putExtra("type", EditInfoActivity.TYPE_EDIT_NAME);
        startActivity(editInfoActivity);
    }
    
    public void editYuYuChatId(View clickedView) {
        Intent editInfoActivity = new Intent(MyInfoActivity.this, EditInfoActivity.class);
        editInfoActivity.putExtra("type", EditInfoActivity.TYPE_EDIT_YUYUCHATID);
        startActivity(editInfoActivity);
    }
    
    public void editSignature(View clickedView) {
        Intent editInfoActivity = new Intent(MyInfoActivity.this, EditInfoActivity.class);
        editInfoActivity.putExtra("type", EditInfoActivity.TYPE_EDIT_SIGNATURE);
        startActivity(editInfoActivity);
    }
    
    public void editGender(View clickedView) {
        Intent editInfoActivity = new Intent(MyInfoActivity.this, EditInfoActivity.class);
        editInfoActivity.putExtra("type", EditInfoActivity.TYPE_EDIT_GENDER);
        startActivity(editInfoActivity);
    }

    public void editArea(View clickedView) {
        Intent editInfoActivity = new Intent(MyInfoActivity.this, EditInfoActivity.class);
        editInfoActivity.putExtra("type", EditInfoActivity.TYPE_EDIT_AREA);
        startActivity(editInfoActivity);
    }
    
    public void userInfoGet() {
        sendRequest(jsonUtil.getUserInfoGetJSON(mMyId));
    }


    

    

    
    @Override
    protected void onDestroy() {
        if(client != null && client.isConnected()) {
            client.disconnect();
            client = null;
        }
        // Dismiss the progress bar when application is closed
        if (prgDialog != null) {
            prgDialog.dismiss();
        }
        super.onDestroy();
    }
    
    /**
     * Connection with the server
     */
    private WebSocketClient client;
    private JSONUtil jsonUtil;
    void startUpClient() {
        if(client != null && client.isConnected()) {
            return;
        }
        jsonUtil = new JSONUtil(getApplicationContext());
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(WsConfig.SESSION_TAG_DEFAULT)), new WebSocketClient.Listener() {
            public void onConnect() {
                if(mMySignature == null) {
                    userInfoGet();
                }
            }
            public void onMessage(String message) {
                parseMessage(message);
            }
            public void onMessage(byte[] data) {
                // Message will be in JSON format
                parseMessage(JSONUtil.bytesToHex(data));
            }
            public void onDisconnect(int code, String reason) {
                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);
                showToast(message);
            }
            public void onError(Exception error) {
                showToast("Error! : " + error);
            }
        }, null);
        client.connect();
    }

    //remove the null judge for immediately send a message after connection setup
    private void sendRequest(String message) {
        client.send(message);
    }
    
    private void parseMessage(final String msg) {
 
        try {
            JSONObject jObj = new JSONObject(msg);
 
            // JSON node 'flag'
            String flag = jObj.getString("flag");

            if (flag.equalsIgnoreCase(JSONUtil.FLAG_USERINFO_GET)) {
                String result = jObj.getString("result");
                showToast(result);
                
                if(result.equalsIgnoreCase("success")) {
                    try {
                        mMyName = jObj.getString("userName");
                        mMySignature = jObj.getString("userSignature");
                        mMyGender = jObj.getString("userGender");
                        mMyArea = jObj.getString("userArea");
                        mYuYuChatId = jObj.getString("yuyuChatId");
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                    
                    mEasyStorage.putString("mMyName", mMyName);
                    mEasyStorage.putString("mMySignature", mMySignature);
                    mEasyStorage.putString("mMyGender", mMyGender);
                    mEasyStorage.putString("mMyArea", mMyArea);
                    mEasyStorage.putString("mYuYuChatId", mYuYuChatId);
                    
                    
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            findViewById(R.id.waiting).setVisibility(View.GONE);
                            mIdView.setText(mYuYuChatId);
                            if(mMyName != null) {
                                mNameView.setText(mMyName);
                            }
                            if(mMyGender != null) {
                                mGenderView.setText(mMyGender);
                            }
                            if(mMyArea != null) {
                                mAreaView.setText(mMyArea);
                            }
                       }
                    });
                }
            } else if (flag.equalsIgnoreCase(JSONUtil.FLAG_USERINFO_MODIFY)) {
                String result = jObj.getString("result");
                showToast(result);
                //go back to the previous activity
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                   }
                });
                
            }
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_SHORT).show();
            }
        });
 
    }
    
    
    //Upload photo methods
    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    
    // When Upload button is clicked
    public void uploadImage(View v) {
        // When Image is selected from Gallery
        if (imgPath != null && !imgPath.isEmpty()) {
            prgDialog.setMessage("Converting Image to Binary Data");
            prgDialog.show();
            // Convert image to String using Base64
            encodeImagetoString();
        // When Image is not selected from Gallery
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    "You must select image from gallery before you try to upload",
                    Toast.LENGTH_LONG).show();
        }
    }
    
    // When Image is selected from Gallery
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data
 
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();
 
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.image_photo_mine);
                // Set the Image in ImageView
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgPath));
                
                //Set the photo background color
                Bitmap photo_mine = ((BitmapDrawable)(mPhotoView.getDrawable())).getBitmap();
                View background_photo_mine = findViewById(R.id.background_photo_mine);
                background_photo_mine.setBackgroundColor(BackgroundUtil.getAverageColor(photo_mine));
                
                // Get the Image's file name
                String fileNameSegments[] = imgPath.split("/");
                fileName = fileNameSegments[fileNameSegments.length - 1];
                // Put file name in Async Http Post Param which will used in Java web app
                params.put("filename", mYuYuChatId+fileName.substring(fileName.indexOf(".")));
 
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }
 
    }
    
 // AsyncTask - To convert Image to String
    public void encodeImagetoString() {
        new AsyncTask<Void, Void, String>() {
 
            protected void onPreExecute() {
 
            };
 
            @Override
            protected String doInBackground(Void... params) {
                BitmapFactory.Options options = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                bitmap = BitmapFactory.decodeFile(imgPath,
                        options);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                // Must compress the Image to reduce image size to make upload easy
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
                byte[] byte_arr = stream.toByteArray();
                // Encode Image to String
                encodedString = Base64.encodeToString(byte_arr, 0);
                return "";
            }
 
            @Override
            protected void onPostExecute(String msg) {
                prgDialog.setMessage("Calling Upload");
                // Put converted Image string into Async Http Post param
                params.put("image", encodedString);
                // Trigger Image upload
                triggerImageUpload();
            }
        }.execute(null, null, null);
    }
    
    public void triggerImageUpload() {
        makeHTTPCall();
    }
    
 // Make Http call to upload Image to Java server
    public void makeHTTPCall() {
        prgDialog.setMessage("Invoking JSP");        
        AsyncHttpClient client = new AsyncHttpClient();
        // Don't forget to change the IP address to your LAN address. Port no as well.
        client.post(WsConfig.UPLOADIMG_HTTP,
                params, new AsyncHttpResponseHandler() {
                    // When the response returned by REST has Http
                    // response code '200'
                    @Override
                    public void onSuccess(String response) {
                      //Inform that my photo is saved locally, if server received my photo
                        //Save the photo bitmap to internal memory
                        mMyPhotoPath = mYuYuChatId + ".jpg";
                        String mMyPhotoName = mMyPhotoPath.substring(0, mMyPhotoPath.indexOf("."));
                        String mMyPhotoExtention = mMyPhotoPath.substring(mMyPhotoPath.indexOf(".")+1);
                        Bitmap photo_mine = ((BitmapDrawable)(mPhotoView.getDrawable())).getBitmap();
                        mEasyStorage.saveImage(photo_mine, mMyPhotoName, mMyPhotoExtention);
//                        showToast("[2]"+mMyPhotoPath);
                        mEasyStorage.putString("mMyPhotoPath", mMyPhotoPath);
//                        showToast("[3]"+mMyPhotoPath);
                        
                        
                        // Hide Progress Dialog
                        prgDialog.hide();
                        Toast.makeText(getApplicationContext(), response,
                                Toast.LENGTH_LONG).show();
                    }
 
                    // When the response returned by REST has Http
                    // response code other than '200' such as '404',
                    // '500' or '403' etc
                    @Override
                    public void onFailure(int statusCode, Throwable error,
                            String content) {
                        // Hide Progress Dialog
                        prgDialog.hide();
                        // When Http response code is '404'
                        if (statusCode == 404) {
                            Toast.makeText(getApplicationContext(),
                                    "Requested resource not found",
                                    Toast.LENGTH_LONG).show();
                        }
                        // When Http response code is '500'
                        else if (statusCode == 500) {
                            Toast.makeText(getApplicationContext(),
                                    "Something went wrong at server end",
                                    Toast.LENGTH_LONG).show();
                        }
                        // When Http response code other than 404, 500
                        else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
                                            + statusCode, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                });
    }
}
